<template>
  <el-dialog
    :close-on-click-modal="false"
    :append-to-body="true"
    title="修改密码"
    width="800px"
    @close="handleCancel"
    :visible.sync="visible"
  >
    <el-form
      :model="form"
      ref="form"
      :rules="rules"
      :label-position="labelPosition"
      label-width="90px"
    >
      <el-form-item label="原始密码" prop="oldPassword">
        <el-input v-model="form.oldPassword" placeholder="请输入旧密码" />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input type="password" v-model="form.newPassword" placeholder="至少6位，且包含数字和字母" />
      </el-form-item>
      <!-- <el-form-item label="确认密码" prop="newSure">
        <el-input type="password" v-model="form.newSure" placeholder="至少6位，且包含数字和字母" />
      </el-form-item>-->
    </el-form>
    <div slot="footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button @click="handleOk" type="primary">修改</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { openNotification } from '@/utils/util'
import { changePass } from '@/api/system'
import md5 from 'js-md5'

export default {
  data() {
    const validPass = (rule, value, callback) => {
      console.log('value', value, this.form)
      if (!value) {
        callback(new Error('请输入新密码'))
      } else if (value.length < 6) {
        callback(new Error('密码至少需要6位'))
      } else if (!((/[a-z]/.test(value) || /[A-Z]/.test(value)) && /[0-9]/.test(value))) {
        callback(new Error('密码里面需包含数字和字母'))
      } else if (this.form.newPassword && this.form.newSure) {
        if (this.form.newPassword !== this.form.newSure) {
          callback(new Error('两次密码不相等'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      visible: false,
      labelPosition: 'right',
      form: {},
      rules: {
        oldPassword: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
        newPassword: [{ required: true, validator: validPass, trigger: 'blur' }]
        // newSure: [{ required: true, validator: validPass, trigger: 'blur' }]
      }
    }
  },
  methods: {
    show() {
      this.visible = true
      this.$nextTick(() => {
        // this.$refs.form.resetFields()
      })
    },
    handleOk() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          let data = Object.assign({}, this.form)

          data.oldPassword = md5(data.oldPassword + 'K004')
          data.newPassword = md5(data.newPassword + 'K004')
          //   data.newSure = md5(data.newSure + 'K004')
          const res = await changePass(data)
          if (res.state === '000000' && res.data) {
            openNotification('success', '修改密码成功，下次登录生效')
            this.visible = false
          } else {
            openNotification('error', res.message)
          }
        }
      })
    },
    handleCancel() {
      this.visible = false
    }
  }
}
</script>
